/*
 * Copyright 2010 Electronic Business Systems Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package gr.ebs.gssdroid.activities;

import gr.ebs.gssdroid.GssDroid;
import gr.ebs.gssdroid.R;
import gr.ebs.gssdroid.async.GssAsyncTask;
import gr.ebs.gssdroid.async.TaskResult;
import gr.ebs.gssdroid.http.GssHttpCommands;
import gr.ebs.gssdroid.http.GssHttpException;
import gr.ebs.gssdroid.http.SystemErrorException;
import gr.ebs.gssdroid.resource.GroupResource;
import gr.ebs.gssdroid.resource.GroupUserResource;
import gr.ebs.gssdroid.resource.GroupsResource;
import gr.ebs.gssdroid.resource.RestResource;
import gr.ebs.gssdroid.widget.GroupsListView;
import gr.ebs.gssdroid.widget.InfoDialog;
import gr.ebs.gssdroid.widget.UserAdapter;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import android.widget.ExpandableListView.OnGroupExpandListener;

public class GssGroups extends AbstractGssActivity{
GroupsListView groupsList;
	
	ProgressDialog myprogress;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, GssMyFolders.MENU_HOME, 0, "Home").setIcon(android.R.drawable.btn_star);
		menu.add(0, GssMyFolders.MENU_LOGIN, 0, "Login").setIcon(android.R.drawable.ic_menu_more);
		menu.add(0, GssMyFolders.MENU_INFO, 0, "About").setIcon(android.R.drawable.ic_menu_info_details);
		menu.add(0, GssMyFolders.MENU_NEW, 0, "Create").setIcon(android.R.drawable.ic_menu_add);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected( MenuItem item) {
		switch (item.getItemId()) {
		case GssMyFolders.MENU_HOME:
			((GssDroid)getParent()).selectTab(0);
			return true;
		case GssMyFolders.MENU_LOGIN:
			handleLogin();
			return true;
		case GssMyFolders.MENU_INFO:
			InfoDialog info = new InfoDialog(this, R.string.infodialog_title, R.string.infodialog_content);
			info.show();
			return true;
		case GssMyFolders.MENU_NEW:
			showNew();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.groups);
		groupsList = ((GroupsListView) findViewById(R.id.groupsListView));
		groupsList.setOnGroupExpandListener(new OnGroupExpandListener() {
			
			@Override
			public void onGroupExpand(int groupPosition) {
				GroupResource g = (GroupResource) groupsList.getListdapter().getGroup(groupPosition);
				if(g!=null){
					getGroupUserTask(groupPosition).execute(g.getUri());
				}
				
			}
		});
		if(getDroidApplication().getUserResource()==null||getDroidApplication().getUserResource().getFilesPath()==null){
			handleLogin();
			finish();
			return;
		}
		getGroupsTask().execute(getDroidApplication().getUserResource().getGroupsPath());
		((TextView) findViewById(R.id.textPath)).setText("Groups");
		ImageButton newButton = (ImageButton)findViewById(R.id.newBottomItem);
		newButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showNew();
			}
		});
		ImageButton refreshButton = (ImageButton)findViewById(R.id.refreshFolder);
		refreshButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				getGroupsTask().execute(getDroidApplication().getUserResource().getGroupsPath());
			}
		});
		registerForContextMenu(groupsList);
	}
	
	private void showNew(){
		final CharSequence[] items = {"New Group"};
		AlertDialog.Builder builder = new AlertDialog.Builder(GssGroups.this);
		builder.setTitle("Create ...");
		builder.setItems(items, new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int item) {
		        switch(item){
		        case 0:
		        	final AlertDialog.Builder alert = new AlertDialog.Builder(GssGroups.this);
		        	alert.setTitle("New Group");
		    		final EditText input = new EditText(GssGroups.this);
		    		alert.setView(input);
		    		alert.setPositiveButton("Create", new DialogInterface.OnClickListener() {
		    			public void onClick(DialogInterface dialog, int whichButton) {
		    				String value = input.getText().toString().trim();
		    				getNewGroupTask().execute(getDroidApplication().getUserResource().getGroupsPath(),value);
		    			}
		    		});

		    		alert.setNegativeButton("Cancel",
		    				new DialogInterface.OnClickListener() {
		    					public void onClick(DialogInterface dialog, int whichButton) {
		    						dialog.cancel();
		    					}
		    				});
		    		alert.show();
		        	break;
		        default:
		        	break;
		        }
		    }
		});
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	private GssAsyncTask getGroupsTask() {
		GssAsyncTask getTrashTask = new GssAsyncTask(getDroidApplication().getUserDetails()) {
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				myprogress = ProgressDialog.show(GssGroups.this, "Fetching Data", "Please Wait", true, false);
			}

			@Override
			protected RestResource doExecution(String[] params) throws Exception {
				GssHttpCommands http = new GssHttpCommands(getDroidApplication().getUserDetails());
				GroupsResource groups = http.getGroupsResource(params[0]);
				return groups;
			}

			@Override
			protected void onPostExecute(TaskResult result) {
				myprogress.hide();
				if (result.getResource() != null)
					groupsList.setGroup(((GroupsResource) result.getResource()));
				else if(result.getException()!=null){}
					//handleRestException("TRASH",result.getException());
				super.onPostExecute(result);
			}
		};
		return getTrashTask;
	}
	
	
	private GssAsyncTask getGroupUserTask(final int groupPosition) {
		GssAsyncTask getTrashTask = new GssAsyncTask(getDroidApplication().getUserDetails()) {
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				myprogress = ProgressDialog.show(GssGroups.this, "Fetching Data", "Please Wait", true, false);
			}

			@Override
			protected RestResource doExecution(String[] params) throws Exception {
				GssHttpCommands http = new GssHttpCommands(getDroidApplication().getUserDetails());
				
				GroupResource group = http.getGroupResource(params[0]);
				for(String pu : group.getUserPaths()){
					GroupUserResource u = http.getGroupUserResource(pu);
					group.getUsers().add(u);
				}
				
				
				return group;
			}

			@Override
			protected void onPostExecute(TaskResult result) {
				myprogress.hide();
				if (result.getResource() != null){
					((GroupResource)groupsList.getListdapter().getGroup(groupPosition)).setUsers(((GroupResource) result.getResource()).getUsers());
					groupsList.getListdapter().notifyDataSetChanged();
					//groupsList.setGroup(((GroupResource) result.getResource()));
				}
				else if(result.getException()!=null){}
					//handleRestException("TRASH",result.getException());
				super.onPostExecute(result);
			}
		};
		return getTrashTask;
	}
	
	protected GssAsyncTask getNewGroupTask() {
		GssAsyncTask getFolderTask = new GssAsyncTask(getDroidApplication().getUserDetails()) {
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				myprogress = ProgressDialog.show(GssGroups.this,
						"Fetching Data", "Please Wait", true, false);
			}

			@Override
			protected RestResource doExecution(String[] params)
					throws Exception {
				new GssHttpCommands(getDroidApplication().getUserDetails()).createNewGroup(params[0],params[1]);
				return null;

			}

			@Override
			protected void onPostExecute(TaskResult result) {
				myprogress.hide();
				if (result.getException() == null)
					getGroupsTask().execute(getDroidApplication().getUserResource().getGroupsPath());
				else if(result.getStatusCode() == 409){
					showErrorDialog("Duplicate Group Name", "A group with the same name already exists.");
				}
				else if(result.getStatusCode() == 404){
					showErrorDialog("No User found", "User with specified username was not found");
				}
				else
					handleRestException("GET", result.getException());
				super.onPostExecute(result);
			}
		};
		return getFolderTask;
	}
	
	protected void handleRestException(String type, Throwable e) {
		String errorMessage = "";
		if (e instanceof SystemErrorException)
			errorMessage = e.getMessage();
		else if (e instanceof GssHttpException)
			if (((GssHttpException) e).getStatusCode() > 0)
				errorMessage = "Status Code:"
						+ ((GssHttpException) e).getStatusCode() + "\n"
						+ e.getMessage();
		AlertDialog alertDialogn = new AlertDialog.Builder(this).create();
		alertDialogn.setTitle("An error occured");
		alertDialogn.setMessage(errorMessage);
		alertDialogn.setButton("Continue",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		alertDialogn.setCancelable(true);
		alertDialogn.show();

	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		
		final RestResource entry = (RestResource) groupsList.getAdapter().getItem((int) ((ExpandableListContextMenuInfo)menuInfo).id);
		if(entry instanceof GroupResource){
			menu.add(100, 1, 2, "Add User");
			menu.add(100, 2, 3, "Delete");
			
		}
		
		/*
		 * AdapterView.AdapterContextMenuInfo info =
		 * (AdapterView.AdapterContextMenuInfo) menuInfo; GssFileListAdapter
		 * adapt = (GssFileListAdapter) ((GssFileListView)
		 * findViewById(R.id.fileListView)) .getAdapter(); final
		 * GssFileListAdapterEntry entry = adapt.getItem(info.position); //
		 * if(entry.file instanceof FolderResource)
		 */

	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item
		.getMenuInfo();
		AlertDialog alertDialog = null;
		final RestResource entry = (RestResource) groupsList.getAdapter().getItem((int) info.id);
		switch (item.getItemId()) {
		// case R.id.new_folder:
		// new
		// NewFolderDialog(GssClient.this,GssClient.this,(FolderResource)currentResource).show();
		// return true;
		case 2:
			alertDialog = new AlertDialog.Builder(this).create();
			alertDialog.setTitle("Delete Group");
			alertDialog
					.setMessage("R u sure you want to delete this group and all its users?");
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					//deleteFolderTask().execute(entry.getUri());
				}
			});
			alertDialog.setButton2("CANCEL",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {

						}
					});
			alertDialog.setCancelable(true);
			alertDialog.show();
			return true;
		case 1:
			final AlertDialog.Builder alert = new AlertDialog.Builder(GssGroups.this);
        	alert.setTitle("Add User");
        	final AutoCompleteTextView input = new AutoCompleteTextView(GssGroups.this);
        	input.setTextColor(Color.BLACK);
    		input.setAdapter(new UserAdapter(GssGroups.this,getDroidApplication().getUserDetails(), new ArrayList<String>(),true));
    		alert.setView(input);
    		alert.setPositiveButton("Add", new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int whichButton) {
    				String value = input.getText().toString().trim();
    				getNewGroupTask().execute(entry.getUri(),value);
    			}
    		});

    		alert.setNegativeButton("Cancel",
    				new DialogInterface.OnClickListener() {
    					public void onClick(DialogInterface dialog, int whichButton) {
    						dialog.cancel();
    					}
    				});
    		alert.show();
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}
	
	public List<String> getGroupNames(){
		List<String> result = new ArrayList<String>();
		for(GroupResource g : groupsList.getGroup().getGroups())
			result.add(g.getName());
		return result;
	}
}
